package com.hkyl.hospital.service.impl;

import com.hkyl.hospital.entity.Permission;
import com.hkyl.hospital.mapper.PermissionMapper;
import com.hkyl.hospital.mapper.custom.CustomRoleMapper;
import com.hkyl.hospital.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hyh
 * @date 2023/07/10 12:10:32
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private CustomRoleMapper roleMapper;
    @Override
    public List<Permission> listPermission() {
        return permissionMapper.selectByExample(null);
    }

    @Override
    public List<Permission> listByRoleId(Integer roleId) {
        return null;
    }

    @Override
    public Integer save(Permission permission) {
        return permissionMapper.insertSelective(permission);
    }

    @Override
    public Integer update(Permission permission) {
        return permissionMapper.updateByPrimaryKeySelective(permission);
    }

    @Override
    public Integer remove(Integer permissionId) {
        return permissionMapper.deleteByPrimaryKey(permissionId);
    }

    @Override
    public Permission getRoot() {
        List<Permission> permissions = listPermission();
        Permission root = getOne(-1);
        setChildren(root, permissions);
        return root;
    }
    private void setChildren(Permission parent, List<Permission> permissions){
        for (Permission permission : permissions) {
            if (permission.getParentId() == parent.getPermissionId()){
                if (parent.getChildren() == null){
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(permission);
                setChildren(permission, permissions);
            }
        }
    }

    @Override
    public Permission getOne(Integer permissionId) {
        return permissionMapper.selectByPrimaryKey(permissionId);
    }

    @Override
    public List<Integer> getPermissionByRoleId(Integer roleId) {
        return roleMapper.selectPermissionByRoleId(roleId);
    }

    @Override
    public Integer distributePermissions(Integer roleId, List<Integer> permissionIds) {
        Integer rows = roleMapper.removePermissionByRoleId(roleId);
        if (permissionIds.size() > 0){
            rows += roleMapper.distributePermissions(roleId, permissionIds);
        }
        return rows;
    }
}
